package tt.dz.egobus.servicemanager.core.filter;

import org.springframework.web.util.WebUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static tt.dz.egobus.servicemanager.core.interceptor.SessionInterceptor.ADMIN_SESSION_KEY;

/**
 * @author Anson
 * @date 17-4-20
 * @name
 * @since 1.0.4
 */
@WebFilter(urlPatterns = "/index.html", filterName = "egobusIndex")
public class EgobusSessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Object adminSession = WebUtils.getSessionAttribute((HttpServletRequest) request,
                ADMIN_SESSION_KEY);
        if (adminSession != null) {
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse)response).sendRedirect(((HttpServletRequest) request).getContextPath()+"/");
        }
    }

    @Override
    public void destroy() {

    }
}
